devfandomcom-20200223-history
Lua reference manual/Scribunto libraries
Scribunto libraries All Scribunto libraries are located in the table mw. Base functions mw.allToString mw.allToString( ... ) Calls tostring() on all arguments, then concatenates them with tabs as separators. mw.clearLogBuffer mw.clearLogBuffer() Removes all data logged with mw.log(). mw.clone mw.clone( value ) Creates a deep copy of a value. All tables (and their metatables) are reconstructed from scratch. Functions are still shared, however. mw.executeFunction mw.executeFunction( func ) This creates a new copy of the frame object, calls the function with that as its parameter, then calls tostring() on all results and concatenates them (no separator) and returns the resulting string. Note this will not work correctly from the debug console, as there is no frame object to copy. mw.executeModule mw.executeModule( func ) Executes the function in a sandboxed environment; the function cannot affect anything in the current environment, with the exception of side effects of calling any existing closures. The name "executeModule" is because this is the function used when a module is loaded from the Module: namespace. mw.getCurrentFrame mw.getCurrentFrame() Returns the current frame object. mw.getLogBuffer mw.getLogBuffer() Returns the data logged by mw.log(), as a string. mw.incrementExpensiveFunctionCount mw.incrementExpensiveFunctionCount() Adds one to the "expensive parser function" count, and throws an exception if it exceeds the limit (see $wgExpensiveParserFunctionLimit). mw.loadData mw.loadData( module ) Sometimes a module needs large tables of data; for example, a general-purpose module to convert units of measure might need a large table of recognized units and their conversion factors. And sometimes these modules will be used many times in one page. Parsing the large data table for every can use a significant amount of time. To avoid this issue, mw.loadData() is provided. mw.loadData works like require(), with the following differences: * The loaded module is evaluated only once per page, rather than once per call. * The loaded module is not recorded in package.loaded. * The value returned from the loaded module must be a table. Other data types are not supported. * The returned table (and all subtables) may contain only booleans, numbers, strings, and other tables. Other data types, particularly functions, are not allowed. * The returned table (and all subtables) may not have a metatable. * All table keys must be booleans, numbers, or strings. * The table actually returned by mw.loadData() has metamethods that provide read-only access to the table returned by the module. Since it does not contain the data directly, pairs() and ipairs() will work but other methods, including #value, next(), and the functions in the Table library, will not work correctly. The hypothetical unit-conversion module mentioned above might store its code in "Module:Convert" and its data in "Module:Convert/data", and "Module:Convert" would use local data = mw.loadData( 'Module:Convert/data' ) to efficiently load the data. mw.log mw.log( ... ) Passes the arguments to mw.allToString(), then appends the resulting string to the log buffer. In the debug console, the function print() is an alias for this function. Frame object The frame object is the interface to the parameters passed to , and to the parser. frame.args A table for accessing the arguments passed to the frame. For example, if a module is called from wikitext with then frame.args1 will return "arg1", frame.args2 will return "arg2", and frame.args'name' (or frame.args.name) will return "arg3". It is also possible to iterate over arguments using pairs( frame.args ) or ipairs( frame.args ). Note that values in this table are always strings; tonumber() may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation: gives string values "1" and "2" indexed by numeric keys 1 and 2. As in MediaWiki template invocations, named arguments will have leading and trailing whitespace removed from both the name and the value before they are passed to Lua, whereas unnamed arguments will not have whitespace stripped. For performance reasons, frame.args is a metatable, not a real table of arguments. Argument values are requested from MediaWiki on demand. This means that most other table methods will not work correctly, including #frame.args, next( frame.args ), and the functions in the Table library. If preprocessor syntax such as template invocations and triple-brace arguments are included within an argument to #invoke, they will be expanded before being passed to Lua. If certain special tags written in XML notation, such as , , and , are included as arguments to #invoke, then these tags will be converted to "strip markers" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke. frame:getParent frame:getParent() Called on the frame created by , returns the frame for the page that called . Called on that frame, returns nil. This lets you just put inside a template and the parameters passed to the template (i.e. ) will be passed straight to the Lua module, without having to include them directly (so, you don't have to do }| }| }}}). Example: * Module:Hello local = p {} function p.hello( frame ) return "Hello, " .. frame:getParent().args1 .. "!" end return p * Template:Hello * Article * This will output "Hello, Wikia!". frame:expandTemplate frame:expandTemplate{ title = title, args = table } Note the use of named args syntactic sugar; see Function calls for details. This is transclusion. The call frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } } does roughly the same thing from Lua that does in wikitext. As in transclusion, if the passed title does not contain a namespace prefix it will be assumed to be in the Template: namespace. Note that the title and arguments are not preprocessed before being passed into the template: -- This is roughtly equivalent to wikitext like -- }} frame:expandTemplate{ title = 'template', args = { '|' } } -- This is roughtly equivalent to wikitext like -- ! }} frame:expandTemplate{ title = 'template', args = { ' ' } } frame:preprocess frame:preprocess( string ) frame:preprocess{ text = string } This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as } are expanded. Certain special tags written in XML-style notation, such as , , and , will be replaced with "strip markers" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke. If you are expanding a single template, use frame:expandTemplate instead of trying to construct a wikitext string to pass to this method. It's faster and less prone to error if the arguments contain pipe characters or other wikimarkup. local p = {} function p.hello( frame ) -- This will preprocess the wikitext and expand the template return frame:preprocess( "Bold and italics is " ) end return p frame:getArgument frame:getArgument( arg ) frame:getArgument{ name = arg } Gets an object for the specified argument, or nil if the argument is not provided. The returned object has one method, object:expand(), that returns the expanded wikitext for the argument. local p = {} function p.hello( frame ) -- |foo= }} local varOne = frame:getArgument( 1 ) local varTwo = frame.args2 local varThree = frame:getArgument( 'foo' ) return varOne:expand() .. varTwo .. varThree:expand() end return p frame:newParserValue frame:newParserValue( text ) frame:newParserValue{ text = text } Returns an object with one method, object:expand(), that returns the result of frame:preprocess( text ). frame:newTemplateParserValue frame:newTemplateParserValue{ title = title, args = table } Returns an object with one method, object:expand(), that returns the result of frame:expandTemplate called with the given arguments. frame:argumentPairs frame:argumentPairs() Same as pairs( frame.args ). Included for backwards compatibility. Language library Language codes are described at Language code. Functions documented as mw.language.name are available on the global mw.language table; functions documented as mw.language:name are methods of a language object (see mw.language.new). Difference from MW core: mw.language.isSupportedLanguage and mw.language.isKnownLanguageTag removed, and mw.language.fetchLanguageName has been modified. mw.language.fetchLanguageName mw.language.fetchLanguageName( code ) The full name of the native language name (language autonym). Difference from MW core: The second parameter, inLanguage, which returns the language name translated in target language if a value is given for it, is not supported due to missing methods in MW 1.19. mw.language.getContentLanguage mw.language.getContentLanguage() mw.getContentLanguage() Returns a new language object for the wiki's default content language. mw.language.isValidBuiltInCode mw.language.isValidBuiltInCode( code ) Returns true if a language code is of a valid form for the purposes of internal customisation of MediaWiki. The code may not actually correspond to any known language. mw.language.isValidCode mw.language.isValidCode( code ) Returns true if a language code string is of a valid form, whether or not it exists. This includes codes which are used solely for customisation via the MediaWiki namespace. The code may not actually correspond to any known language. mw.language.new mw.language.new( code ) mw.getLanguage( code ) Creates a new language object. Language objects do not have any publicly accessible properties, but they do have several methods, which are documented below. mw.language:getCode lang:getCode() Returns the language code for this language object. mw.language:isRTL lang:isRTL() Returns true if the language is written right-to-left, false if it is written left-to-right. mw.language:lc lang:lc( s ) Converts the string to lowercase, honoring any special rules for the given language. When the Ustring library is loaded, the mw.ustring.lower() function is implemented as a call to mw.language.getContentLanguage():lc( s ). mw.language:lcfirst lang:lcfirst( s ) Converts the first character of the string to lowercase, as with lang:lc(). mw.language:uc lang:uc( s ) Converts the string to uppercase, honoring any special rules for the given language. When the Ustring library is loaded, the mw.ustring.upper() function is implemented as a call to mw.language.getContentLanguage():uc( s ). mw.language:ucfirst lang:ucfirst( s ) Converts the first character of the string to uppercase, as with lang:uc(). mw.language:caseFold lang:caseFold( s ) Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed. mw.language:formatNum lang:formatNum( n ) Formats a number with grouping and decimal separators appropriate for the given language. Given 123456.78, this may produce "123,456.78", "123.456,78", or even something like "١٢٣٬٤٥٦٫٧٨" depending on the language and wiki configuration. mw.language:formatDate lang:formatDate( format, timestamp, local ) Formats a date according to the given format string. If timestamp is omitted, the default is the current time. The valur for local must be a boolean or nil; if true, the time is formatted in the server's local time rather than in UTC. The format string and supported values for timestamp are identical to those for the #time parser function from Extension:ParserFunctions. Note that backslashes may need to be doubled in the Lua string where they wouldn't in wikitext: -- This outputs a newline, where would output a literal "n" lang:formatDate( '\n' ) -- This outputs a literal "n", where would output a backslash -- followed by the month number. lang:formatDate( '\\n' ) -- This outputs a backslash followed by the month number, where -- would output two backslashes followed by the month number. lang:formatDate( '\\\\n' ) mw.language:parseFormattedNumber lang:parseFormattedNumber( s ) This takes a number as formatted by lang:formatNum() and returns the actual number. In other words, this is basically a language-aware version of tonumber(). mw.language:convertPlural lang:convertPlural( n, ... ) lang:convertPlural( n, forms ) lang:plural( n, ... ) lang:plural( n, forms ) This chooses the appropriate grammatical form from forms (which must be a sequence table) or ... based on the number n. For example, in English you might use n .. ' ' .. lang:plural( n, 'sock', 'socks' ) or n .. ' ' .. lang:plural( n, { 'sock', 'socks' } ) to generate grammatically-correct text whether there is only 1 sock or 200 socks. The necessary values for the sequence are language-dependent, see mw:Help:Magic words#Language-dependent word conversions and translatewiki:FAQ#PLURAL for some details. mw.language:convertGrammar lang:convertGrammar( word, case ) lang:grammar( case, word ) : Note the different parameter order between the two aliases. convertGrammar matches the order of the method of the same name on MediaWiki's Language object, while grammar matches the order of the parser function of the same name, documented at mw:Help:Magic words#Localisation. This chooses the appropriate inflected form of word for the given inflection code case. The possible values for word and case are language-dependent, see mw:Help:Magic words#Language-dependent word conversions and translatewiki:Grammar for some details. mw.language:gender lang:gender( what, masculine, feminine, neutral ) lang:gender( what, { masculine, feminine, neutral } ) Chooses the string corresponding to the gender of what, which may be "male", "female", or a registered user name. Site library mw.site.currentVersion A string holding the current version of MediaWiki. mw.site.scriptPath The value of $wgScriptPath. mw.site.server The value of $wgServer. mw.site.siteName The value of $wgSitename. mw.site.stylePath The value of $wgStylePath. mw.site.namespaces Table holding data for all namespaces, indexed by number. The data available is: * id: Namespace number. * name: Local namespace name. * canonicalName: Canonical namespace name. * displayName: Set on namespace 0, the name to be used for display (since the name is often the empty string). * hasSubpages: Whether subpages are enabled for the namespace. * hasGenderDistinction: Whether the namespace has different aliases for different genders. * isCapitalized: Whether the first letter of pages in the namespace is capitalized. * isContent: Whether this is a content namespace. * isIncludable: Whether pages in the namespace can be transcluded. * isMovable: Whether pages in the namespace can be moved. * isSubject: Whether this is a subject namespace. * isTalk: Whether this is a talk namespace. * defaultContentModel: The default content model for the namespace, as a string. * aliases: List of aliases for the namespace. * subject: Reference to the corresponding subject namespace's data. * talk: Reference to the corresponding talk namespace's data. * associated: Reference to the associated namespace's data. A metatable is also set that allows for looking up namespaces by name (localized or canonical). For example, both mw.site.namespaces4 and mw.site.namespaces.Project will return information about the Project namespace. mw.site.contentNamespaces Table holding just the content namespaces, indexed by number. See mw.site.namespaces for details. mw.site.subjectNamespaces Table holding just the subject namespaces, indexed by number. See mw.site.namespaces for details. mw.site.talkNamespaces Table holding just the talk namespaces, indexed by number. See mw.site.namespaces for details. mw.site.stats Table holding site statistics. Available statistics are: * pages: Number of pages in the wiki. * articles: Number of articles in the wiki. * files: Number of files in the wiki. * edits: Number of edits in the wiki. * views: Number of views in the wiki. Not available if $wgDisableCounters is set. * users: Number of users in the wiki. * activeUsers: Number of active users in the wiki. * admins: Number of users in group 'sysop' in the wiki. mw.site.stats.pagesInCategory mw.site.stats.pagesInCategory( category, which ) : This function is expensive Gets statistics about the category. If which is unspecified, nil, or "*", returns a table with the following properties: * all: Total pages, files, and subcategories. * subcats: Number of subcategories. * files: Number of files. * pages: Number of pages. If which is one of the above keys, just the corresponding value is returned instead. Each new category queried will increment the expensive function count. mw.site.stats.pagesInNamespace mw.site.stats.pagesInNamespace( ns ) Returns the number of pages in the given namespace (specify by number). mw.site.stats.usersInGroup mw.site.stats.usersInGroup( group ) Returns the number of users in the given group. Uri library mw.uri.encode mw.uri.encode( s, enctype ) Percent-encodes the string. The default type, "QUERY", encodes spaces using '+' for use in query strings; "PATH" encodes spaces as %20; and "WIKI" encodes spaces as '_'. Note that the "WIKI" format is not entirely reversable, as both spaces and underscores are encoded as '_'. mw.uri.decode mw.uri.decode( s, enctype ) Percent-decodes the string. The default type, "QUERY", decodes '+' to space; "PATH" does not perform any extra decoding; and "WIKI" decodes '_' to space. mw.uri.anchorEncode mw.uri.anchorEncode( s ) Encodes a string for use in a MediaWiki URI fragment. mw.uri.buildQueryString mw.uri.buildQueryString( table ) Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false. mw.uri.parseQueryString mw.uri.parseQueryString( s ) Decodes a query string to a table. Keys in the string without values will have a value of false; keys repeated multiple times will have sequence tables as values; and others will have strings as values. mw.uri.canonicalUrl mw.uri.canonicalUrl( page, query ) Returns a URI object for the canonical url for a page, with optional query string/table. mw.uri.fullUrl mw.uri.fullUrl( page, query ) Returns a URI object for the full url for a page, with optional query string/table. mw.uri.localUrl mw.uri.localUrl( page, query ) Returns a URI object for the local url for a page, with optional query string/table. mw.uri.new mw.uri.new( s ) Constructs a new URI object for the passed string or table. See the description of URI objects for the possible fields for the table. mw.uri.validate mw.uri.validate( table ) Validates the passed table (or URI object). Returns a boolean indicating whether the table was valid, and on failure a string explaining what problems were found. URI object The URI object has the following fields, some or all of which may be nil: * protocol: String protocol/scheme * user: String user * password: String password * host: String host name * port: Integer port * path: String path * query: A table, as from mw.uri.parseQueryString * fragment: String fragment. The following properties are also available: * userInfo: String user and password * hostPort: String host and port * authority: String user, password, host, and port * queryString: String version of the query table * relativePath: String path, query string, and fragment tostring() will give the URI string. Methods of the URI object are: mw.uri:parse uri:parse( s ) Parses a string into the current URI object. Any fields specified in the string will be replaced in the current object; fields not specified will keep their old values. mw.uri:clone uri:clone() Makes a copy of the URI object. mw.uri:extend uri:extend( parameters ) Merges the parameters table into the object's query table. Ustring library The ustring library is intended to be a direct reimplementation of the standard String library, except that the methods operate on characters in UTF-8 encoded strings rather than bytes. Most functions will raise an error if the string is not valid UTF-8; exceptions are noted. mw.ustring.maxPatternLength The maximum allowed lengh of a pattern, in bytes. mw.ustring.maxStringLength The maximum allowed lengh of a string, in bytes. mw.ustring.byte mw.ustring.byte( s, i, j ) Returns individual bytes; identical to string.byte(). mw.ustring.byteoffset mw.ustring.byteoffset( s, l, i ) Returns individual the byte offset of a character in the string. The default for both l and i is 1. i may be negative, in which case it counts from the end of the string. The character at l 1 is the first character starting at or after byte i; the character at l 0 is the first character starting at or before byte i. Note this may be the same character. Greater or lesser values of l are calculated relative to these. mw.ustring.char mw.ustring.char( ... ) Much like string.char(), except that the integers are Unicode codepoints rather than byte values. mw.ustring.codepoint mw.ustring.codepoint( s, i, j ) Much like string.byte(), except that the return values are codepoints and the offsets are characters rather than bytes. mw.ustring.find mw.ustring.find( s, pattern, init, plain ) Much like string.find(), except that the pattern is extended as described in Ustring patterns and the init offset is in characters rather than bytes. mw.ustring.format mw.ustring.format( format, ... ) Identical to string.format(). Widths and precisions for strings are expressed in bytes, not codepoints. mw.ustring.gcodepoint mw.ustring.gcodepoint( s, i, j ) Returns three values for iterating over the codepoints in the string. i defaults to 1, and j to -1. This is intended for use in the iterator form of for: for codepoint in mw.ustring.gcodepoint( s ) do block end mw.ustring.gmatch mw.ustring.gmatch( s, pattern ) Much like string.gmatch(), except that the pattern is extended as described in Ustring patterns. mw.ustring.gsub mw.ustring.gsub( s, pattern, repl, n ) Much like string.gsub(), except that the pattern is extended as described in Ustring patterns. mw.ustring.isutf8 mw.ustring.isutf8( s ) Returns true if the string is valid UTF-8, false if not. mw.ustring.len mw.ustring.len( s ) Returns the length of the string in codepoints, or nil if the string is not valid UTF-8. mw.ustring.lower mw.ustring.lower( s ) Much like string.lower(), except that all characters with lowercase to uppercase definitions in Unicode are converted. If the Language library is also loaded, this will instead call lc() on the default language object. mw.ustring.match mw.ustring.match( s, pattern, init ) Much like string.match(), except that the pattern is extended as described in Ustring patterns and the init offset is in characters rather than bytes. mw.ustring.rep mw.ustring.rep( s, n ) Identical to string.rep(). mw.ustring.sub mw.ustring.sub( s, i, j ) Much like string.sub(), except that the offsets are characters rather than bytes. mw.ustring.toNFC mw.ustring.toNFC( s ) Converts the string to Normalization Form C. Returns nil if the string is not valid UTF-8. mw.ustring.toNFD mw.ustring.toNFD( s ) Converts the string to Normalization Form D. Returns nil if the string is not valid UTF-8. mw.ustring.upper mw.ustring.upper( s ) Much like string.upper(), except that all characters with uppercase to lowercase definitions in Unicode are converted. If the Language library is also loaded, this will instead call uc() on the default language object. Ustring patterns Patterns in the ustring functions use the same syntax as the String library patterns. The major difference is that the character classes are redefined in terms of Unicode character properties: * %a: represents all characters with General Category "Letter". * %c: represents all characters with General Category "Control". * %d: represents all characters with General Category "Decimal Number". * %l: represents all characters with General Category "Lowercase Letter". * %p: represents all characters with General Category "Punctuation". * %s: represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed. * %u: represents all characters with General Category "Uppercase Letter". * %w: represents all characters with General Category "Letter" or "Decimal Number". * %x: adds fullwidth character versions of the hex digits. In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as ０-９, patterns such as %b«», and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes. HTML library mw.html is a fluent interface for building complex HTML from Lua. A mw.html object can be created using mw.html.create. Functions documented as mw.html.name are available on the global mw.html table; functions documented as mw.html:name are methods of an mw.html object (see mw.html.create). A basic example could look like this: local div = mw.html.create( 'div' ) div :attr( 'id', 'testdiv' ) :css( 'width', '100%' ) :wikitext( 'Some text' ) :tag( 'hr' ) return tostring( div ) -- Output: Some text mw.html.create mw.html.create( tagName, args ) Creates a new mw.html object containing a tagName html element. You can also pass an empty string as tagName in order to create an empty mw.html object. args can be a table with the following keys: * args.selfClosing: Force the current tag to be self-closing, even if mw.html doesn't recognize it as self-closing * args.parent: Parent of the current mw.html instance (intended for internal usage) mw.html:node html:node( builder ) Appends a child mw.html (builder) node to the current mw.html instance. mw.html:wikitext html:wikitext( ... ) Appends an undetermined number of wikitext strings to the mw.html object. mw.html:newline html:newline() Appends a newline to the mw.html object. mw.html:tag html:tag( tagName, args ) Appends a new child node with the given tagName to the builder, and returns a mw.html instance representing that new node. The args parameter is identical to that of mw.html.create mw.html:attr html:attr( name, value ) html:attr( table ) Set an HTML attribute with the given name and value on the node. Alternatively a table holding name->value pairs of attributes to set can be passed. mw.html:getAttr html:getAttr( name ) Get the value of a html attribute previously set using html:attr() with the given name. mw.html:addClass html:addClass( class ) Adds a class name to the node's class attribute. mw.html:css html:css( name, value ) html:css( table ) Set a CSS property with the given name and value on the node. Alternatively a table holding name->value pairs of properties to set can be passed. mw.html:cssText html:cssText( css ) Add some raw css to the node's style attribute. mw.html:done html:done() Returns the parent node under which the current node was created. Like jQuery.end, this is a convenience function to allow the construction of several child nodes to be chained together into a single statement. mw.html:allDone html:allDone() Like html:done(), but traverses all the way to the root node of the tree and returns it. Reference manual - Scribunto libraries